package com.wmh.baseservice.operationaid.controller;

import com.alibaba.fastjson2.JSON;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.operationaid.entity.KeyWord;
import com.wmh.baseservice.operationaid.pojo.vo.keyWord.KeyWordCreateReqVO;
import com.wmh.baseservice.operationaid.service.KeyWordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.wmh.baseservice.common.utils.returnbody.ReturnBody.success;

/**
 * @author 谢骏
 * @date 2023/6/21 16:14
 **/
@Validated
@RestController
@RequestMapping("public/")
@Api(tags = "运营助手-公开接口(用于机器请求)")
@Slf4j
public class PublicController {

    @Resource
    private KeyWordService keyWordService;

    @ApiOperation("添加关键词数据")
    @PostMapping("operationAid/KeyWord/add")
    public String add(String categoryName, String dataList) {
        List<KeyWordCreateReqVO> list = JSON.parseArray(dataList, KeyWordCreateReqVO.class);
        String cycle = list.get(0).getCycle();
        List<KeyWord> exitsKeys = keyWordService.list(new LambdaQueryWrapperX<KeyWord>()
                .select(KeyWord::getName, KeyWord::getId)
                .eq(KeyWord::getCycle, cycle)
                .eq(KeyWord::getCategoryName, categoryName));
        List<KeyWord> keyWords = list.stream().map(item -> {
            KeyWord keyWord = new KeyWord();
            BeanUtils.copyProperties(item, keyWord);
            Optional<KeyWord> like = exitsKeys.stream().filter(i -> Objects.equals(i.getName(), item.getName())).findFirst();
            like.ifPresent(word -> keyWord.setId(word.getId()));
            keyWord.setCategoryName(categoryName);
            return keyWord;
        }).collect(Collectors.toList());
        keyWordService.saveOrUpdateBatch(keyWords);
        return success();
    }
}
